package com.itheima.book.controller;

import com.itheima.book.utils.result.Result;
import com.itheima.book.pojo.entity.Book;
import com.itheima.book.service.BookService;
import com.itheima.book.pojo.dto.BooksPageQueryDTO;
import com.itheima.book.utils.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/api/myposts")
@Api(tags = "我的发布相关接口")
public class MypostsController {

    @Autowired
    private BookService bookService;
    /**
     * 查询我的发布列表
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("查询我的发布列表")
    public Result<PageHelper<Book>> GetMypostList(
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String searchQuery,
            @RequestParam(required = false, defaultValue = "newest") String sortBy) {
        log.info("查询我的发布列表: currentPage={}, pageSize={}, searchQuery={}, sortBy={}", 
                currentPage, pageSize, searchQuery, sortBy);
        
        // 构建查询DTO
        BooksPageQueryDTO queryDTO = new BooksPageQueryDTO();
        queryDTO.setCurrentPage(currentPage);
        queryDTO.setPageSize(pageSize);
        queryDTO.setSearchQuery(searchQuery);
        queryDTO.setSortBy(sortBy);
        
        // 调用service层方法
        PageHelper<Book> pageHelper = bookService.getUserId(queryDTO);
        return Result.success(pageHelper);
    }

    /**
     * 新增书籍
     * @param book
     * @return
     */
    @PostMapping("/book/save")
    @ApiOperation("新增书籍")
    public Result SaveMypostList(@RequestBody Book book) {
        log.info("新增书籍:{}",book);
        bookService.savebook(book);
        return Result.success();
    }
    /**
     * 编辑书籍
     * @param book
     * @return
     */
    @PutMapping("/book/update")
    @ApiOperation("编辑书籍")
    public Result UpdateMypostList(@RequestBody Book book) {
        log.info("编辑书籍id:{}",book.getId());
        bookService.updateById(book);
        return Result.success();
    }
    /**
     * 下架书籍
     * @param id
     * @return
     */
    @DeleteMapping("/book/{id}")
    @ApiOperation("下架书籍")
    public Result DeleteMypostList(@PathVariable Long id) {
        log.info("下架书籍id:{}",id);
        bookService.removeById(id);
        return Result.success();
    }
}
